/*
 * @(#)KeyInfo.java  2010/11/22
 *
 * Copyright (c) 2010. i2finance., Ltd. All rights reserved.
 */

package com.TTBook.utils.keygen;

import com.TTBook.utils.keygen.adapter.SerialGeneratorDataAdapter;

public class SerialInfo {
    private long keyMax = 0;
    private long keyMin = 0;
    private long nextKey = 0;
    private int poolSize = 5;
    private String keyName = null;
    private SerialGeneratorDataAdapter dataAdapter = null;

    public SerialInfo(int poolSize, String keyName,SerialGeneratorDataAdapter dataAdapter) {
        this.poolSize = poolSize;
        this.keyName = keyName;
        this.dataAdapter=dataAdapter;
        //retrieveFromDB();
    }

    public long getKeyMax() {
        return keyMax;
    }

    public long getKeyMin() {
        return keyMin;
    }

    public int getPoolSize() {
        return poolSize;
    }

    public String getKeyName() {
        return keyName;
    }

    public synchronized long getNextKey() {
        //Lazy Loading,comment retrieveFromDB() in constructor.
        if(nextKey==0){
            retrieveFromDB();
        }
        
        if (nextKey > keyMax) {
            retrieveFromDB();
        }
        return nextKey++;
    }

    private void retrieveFromDB() {
        long keyStart = dataAdapter.getSerialValue(this);
        keyMax = keyStart;
        keyMin = keyStart - poolSize + 1;
        nextKey = keyMin;
    }
}